from rest_framework import serializers

from utils.handlers.swagger import BaseResponseSerializer


def data_response_decorator(many=False, ref_name=None):
    def set_func(cls):
        cls_ref_name = cls.__name__
        if ref_name is not None:
            cls_ref_name = ref_name
        elif getattr(cls, "Meta", None) is not None:
            if getattr(cls.Meta, "ref_name", None) is not None:
                cls_ref_name = cls.Meta.ref_name

        if cls_ref_name.endswith('Serializer'):
            cls_ref_name = cls_ref_name[:-len('Serializer')]
        if cls_ref_name.endswith('Data'):
            cls_ref_name = cls_ref_name[:-len('Data')]

        if not hasattr(cls, 'Meta'):
            class Meta:
                ref_name = cls_ref_name + 'Data'

            setattr(cls, 'Meta', Meta)
        else:
            cls.Meta.ref_name = cls_ref_name + 'Data'

        class AutoDataResponse(BaseResponseSerializer):
            if many:
                data = serializers.ListSerializer(child=cls())
            else:
                data = cls()

            class Meta:
                ref_name = cls_ref_name

        return AutoDataResponse

    return set_func
